<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +-----------------------------------------------------------------
// | 通信库(1.0)
// +-----------------------------------------------------------------
// | Copyright: (c) 2016 Genxin, Inc. All Rights Reserved.
// +-----------------------------------------------------------------
// | PHP version: 5.5
// +-----------------------------------------------------------------
// | Encoding: UTF-8
// +-----------------------------------------------------------------
// | Authors: Geng Xin <gengxin55200@126.com>
// +-----------------------------------------------------------------
//
// $Id: $

header("Content-Type:text/html; charset=UTF-8");

/**
 * 发送短信(创蓝)
 *
 * @param $mobile
 * @param $msg
 *
 * @return bool
 */
function sendMessageService($mobile, $msg)
{
    $url = C('SYS_SMS.URL');
    $param = array(
        'account'    => C('SYS_SMS.ACCOUNT'),
        'pswd'       => C('SYS_SMS.PASSWORD'),
        'mobile'     => $mobile,
        'msg'        => $msg,
        'needstatus' => C('SYS_SMS.STATUS')
    );

    $res = extCurlGet($url, $param);

    return $res;
}

/**
 * 发送邮件
 *
 * @param string $to      发给谁
 * @param string $sub     主题
 * @param string $content 内容
 *
 * @return mixed
 */
function sendMail($to, $sub, $content)
{
    if ($to && $sub && $content) {
        Vendor('PHPMailer.PHPMailerAutoload');
        $mail = new \PHPMailer();
        $mail->IsSMTP();
        $mail->Host = C('SYS_MAIL.HOST');
        $mail->SMTPAuth = C('SYS_MAIL.SMTP_AUTH');
        $mail->Username = C('SYS_MAIL.USER_NAME');
        $mail->Password = C('SYS_MAIL.PASSWORD');
        $mail->From = C('SYS_MAIL.FROM');
        $mail->FromName = C('SYS_MAIL.FROM_NAME');
        $mail->AddAddress($to, '尊敬的客户');
        $mail->WordWrap = C('SYS_MAIL.WORDWRAP');
        $mail->IsHTML(C('SYS_MAIL.IS_HTML'));
        $mail->CharSet = C('SYS_MAIL.CHARSET');
        $mail->Subject = $sub;
        $mail->Body = $content;
        $mail->AltBody = '这是一个纯文本的身体在非营利的HTML电子邮件客户端'; // 邮件正文不支持HTML的备用显示
        $res = $mail->Send();
        if ($res) {
            return true;
        } else {
            return $mail->ErrorInfo;
        }
    } else {
        return false;
    }
}

/**
 * 接口调用(POST请求方式)
 *
 * @param string $relativeURL 相对URL地址
 * @param string $param       入口参数
 * @param int    $system      系统:如果不传，默认走运营中心
 *
 * @return mixed
 */
function callAPI($relativeURL, $param, $system = 1) {
    $param = addToken($param);
    switch ($system) {
        case 1:
            // 与运营中心进行通信
            $data = extCurlPost(C('OPERATER_SERVER_HOST') . $relativeURL, $param);
            break;
        case 2:
            // 与商家中心进行通信
            $data = extCurlPost(C('BUCENTER_SERVER_HOST') . $relativeURL, $param);
            break;
        case 3:
            // 与代理体系进行通信
            $data = extCurlPost(C('AGENT_SERVER_HOST') . $relativeURL, $param);
            break;
        case 4:
            // 与客商通进行通信
            $data = extCurlPost(C('KST_SERVER_HOST') . $relativeURL, $param);
            break;
        default:
            return "接口调用失败，请检查参数";
            break;
    }
    return json_decode($data, true);
}

/**
 * curl POST 操作方法
 *
 * @param $url
 * @param array $param
 * @return mixed|string
 */
function extCurlPost($url, $param = array())
{
    $param = addToken($param);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $param);

    $data = curl_exec($curl);
    if (0 === strpos(bin2hex($data), 'efbbbf')) {
        $data = substr($data, 3);
    }

    curl_close($curl);
    $data = str_replace('\r\n', '<br>', $data);
    return $data;
}

/**
 * GET
 *
 * @param $url
 * @param array $param
 * @return mixed
 */
function extCurlGet($url, $param = array())
{
    $r = '';
    foreach ($param as $key => $val) {
        if ($val !== end($param)) {
            $r .= $key . '=' . $val . '&';
        } else {
            $r .= $key . '=' . $val;
        }
    }
    if (!empty($r) && !is_null($r)) {
        $url .= '?' . $r;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    return $info;
}

/**
 * 生成签名
 *
 * @param $params
 * @return string
 */
function generalToken($params)
{
    $appKey = C('SYS_SALT');
    $signStr = '';
    ksort($params);    // http://www.w3school.com.cn/php/func_array_ksort.asp
    foreach ($params as $key => $value) {
        if ($key != "token") {
            $signStr .= $key . "=" . $value . "&";
        }
    }
    return strtolower(md5($appKey . $signStr));
}

/**
 * 为数组增加签名
 *
 * @param $param
 * @return mixed
 */
function addToken($param)
{
    $param['token'] = generalToken($param);
    return $param;
}

/**
 * URL验签
 *
 * @param $mode
 * @return bool
 */
function validateToken($mode = 'get')
{
//    if (APP_DEBUG) {
//        return true;
//    }
    $get  = I('get.');  // 获取get
    $post = I('post.'); // 获取post
    switch ($mode) {
        case 'get':
            if (!IS_GET) {
//                var_dump("1");
                return false;
            }
            break;
        case 'post':
            if (!IS_POST) {
//                var_dump("2");
                return false;
            }
            break;
        case 'ajax':
            if (!IS_AJAX) {
//                var_dump("3");
                return false;
            }
            break;
        default:
            return false;
    }
    $param = array_merge($get, $post);
    if (empty($param['token'])) {
        return false;
    } else {
        $token = generalToken($param);
        if ($token == $param['token']) {
            return true;
        } else {
            return false;
        }
    }
}